package com.ruoyi.business.youdaoController;

import ask.RtaRequestOuterClass;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.util.JsonFormat;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SaveType;
import com.ruoyi.common.utils.GetUrlParam;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.vo.R;
import com.ruoyi.system.protocol.IDynamicSearchService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("ownKuaiShouApi")
public class YouDaoKuaiShouController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IDynamicSearchService dynamicSearchService;

    private final static String CLASSESEN = "youdao";


    @Log(title = "唯品会", businessType = BusinessType.RTA, esIndex = "weipinhui_log", saveType = SaveType.ES)
    @RequestMapping("/rta")
    public Object rtaSend(HttpServletRequest request) throws Exception {
        String queryString = request.getQueryString();
        String channelId = request.getParameter("channelId");
        String dmpid = request.getParameter("dmpid");
        if(StringUtils.isBlank(channelId) || "null".equals(channelId)){
            return R.failure().msg("channelId不能为空");
        }
        if(StringUtils.isBlank(dmpid) || "null".equals(dmpid)){
            return R.failure().msg("dmpid不能为空");
        }

        Map<String, Object> baseParamsMap = GetUrlParam.queryStrToMap(queryString);

        baseParamsMap.remove("channelId");
        baseParamsMap.remove("dmpid");

        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);
        if(channelDetail == null){
            return R.failure().msg("channelId不正确");
        }
        String url = channelDetail.get("rta_adress") + "";
        String requestAddress = GetUrlParam.getRequestAddress(url);
        String staticParameters = GetUrlParam.TruncateUrlPage(url);
        Map<String, Object> staticParamsMap = GetUrlParam.queryStrToMap(staticParameters);
        baseParamsMap.putAll(staticParamsMap);

        String reportResultsStr = "";
        reportResultsStr = sendProtobufRequest(requestAddress, baseParamsMap);
        JSONObject reportResults = null;
        try {
            reportResults = JSONObject.parseObject(reportResultsStr);
            if(reportResults.getInteger("status_code") == 0){
                JSONArray jsonArray = reportResults.getJSONArray("promotion_result");
                Boolean accept = jsonArray.getJSONObject(0).getBoolean("accept");
                if(accept){
                    return 1;
                }
                return 0;
            }
            return 0;
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    public String sendProtobufRequest(String url, Map<String, Object> params) throws Exception {
//        String url = "https://material-api.test.gifshow.com/rest/n/rta/common/kfy";  // 测试环境
//        String requestId = "00000298d27e48be9d4bb2180395357b";  // 请求Id
//        String channel = "QUANNENG";  // 渠道标识，需向快手技术申请
//        String token = "Abcdefg";  // 渠道标识令牌
        //promotionType 推广类型
        String channel = getMapValue(params, "channel");
        String requestId = getMapValue(params, "dmpid");
        String token = getMapValue(params, "token");
        String idfa = getMapValue(params, "idfa");
        String imei = getMapValue(params, "imei");
        String oaid = getMapValue(params, "oaid");
        String promotionType = getMapValue(params, "promotionType");


        // 构建请求
        RtaRequestOuterClass.RtaRequest.Builder builder = RtaRequestOuterClass.RtaRequest.newBuilder();
        builder.setRequestId(requestId);
        builder.setChannel(channel);
        long requestTime = System.currentTimeMillis();
        builder.setRequestTime(requestTime);
        String sign = requestId + requestTime + token;
        String signKey = DigestUtils.md5DigestAsHex(sign.getBytes()).toLowerCase();
        builder.setSign(signKey);

        // 构建设备标识
        RtaRequestOuterClass.RtaRequest.Device.Builder deviceBuilder = RtaRequestOuterClass.RtaRequest.Device.newBuilder();
        if(StringUtils.isNotBlank(idfa) && !"null".equals(idfa) && !"__IDFA__".equals(idfa)) {
            deviceBuilder.setIdfa(idfa);
            deviceBuilder.setIdfaMd5(DigestUtils.md5DigestAsHex(idfa.getBytes()).toLowerCase());
        }
        if(StringUtils.isNotBlank(imei) && !"null".equals(imei) && !"__IMEI__".equals(imei)) {
            deviceBuilder.setImei(imei);
            deviceBuilder.setImeiMd5(DigestUtils.md5DigestAsHex(imei.getBytes()).toLowerCase());
        }
        if(StringUtils.isNotBlank(oaid) && !"null".equals(oaid) && !"__OAID__".equals(oaid)) {
            deviceBuilder.setOaid(oaid);
            deviceBuilder.setOaidMd5(DigestUtils.md5DigestAsHex(oaid.getBytes()).toLowerCase());
        }

        builder.setDevice(deviceBuilder.build());
        builder.addPromotionType(promotionType);

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost request = new HttpPost(url);
        request.addHeader("content-type", "application/x-protobuf");
        request.setEntity(new ByteArrayEntity(builder.build().toByteArray()));
        CloseableHttpResponse response = client.execute(request);
        client.close();
        // 解析响应
        HttpEntity entity = response.getEntity();
        byte[] bytes = EntityUtils.toByteArray(entity);
        RtaRequestOuterClass.RtaResponse rtaResponse = RtaRequestOuterClass.RtaResponse.parseFrom(bytes);
        String res = JsonFormat.printer().print(rtaResponse);
        return res;

    }


    @Log(title = "有道", businessType = BusinessType.RTA, esIndex = "youdao_log", saveType = SaveType.ES)
    @RequestMapping("/send")
    public Object send(HttpServletRequest request) throws Exception {
        String queryString = request.getQueryString();
        String channelId = request.getParameter("channelId");
        String dmpid = request.getParameter("dmpid");
        if(StringUtils.isBlank(channelId) || "null".equals(channelId)){
            return R.failure().msg("channelId不能为空");
        }
        if(StringUtils.isBlank(dmpid) || "null".equals(dmpid)){
            return R.failure().msg("dmpid不能为空");
        }

        Map<String, Object> baseParamsMap = GetUrlParam.queryStrToMap(queryString);
        //imei\idfa\sid 如果都为111111111111 则返回body为1
        String imei = getMapValue(baseParamsMap, "imei");
        String idfa = getMapValue(baseParamsMap, "idfa");
        String sid = getMapValue(baseParamsMap, "sid");
        if("111111111111".equals(imei) && "111111111111".equals(idfa) && "111111111111".equals(sid)){
            return 1;
        }
        if("222222222222".equals(imei) && "222222222222".equals(idfa) && "222222222222".equals(sid)){
            return 0;
        }


        baseParamsMap.remove("channelId");
        baseParamsMap.remove("dmpid");

        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);
        if(channelDetail == null){
            return R.failure().msg("channelId不正确");
        }
        String url = channelDetail.get("rta_adress") + "";
        String requestType = channelDetail.get("request_type") + "";
        String requestAddress = GetUrlParam.getRequestAddress(url);
        String staticParameters = GetUrlParam.TruncateUrlPage(url);
        Map<String, Object> staticParamsMap = GetUrlParam.queryStrToMap(staticParameters);
        baseParamsMap.putAll(staticParamsMap);



        String ua = baseParamsMap.get("ua") + "";
        String ip = baseParamsMap.get("ip") + "";
        if(StringUtils.isNotBlank(ua) && !"null".equals(ua)){
            ua = URLDecoder.decode(ua, Constants.UTF8);
        }else{
            ua = null;
        }
        if(StringUtils.isNotBlank(ip) && !"null".equals(ip)){
        }else{
            ip = null;
        }
        baseParamsMap.put("reqId", dmpid);
        if(StringUtils.isNotBlank(idfa)){
            baseParamsMap.put("idfa", idfa.toUpperCase());
        }
        if(StringUtils.isNotBlank(imei)){
            //imei转大写
            imei = imei.toUpperCase();
            //imei进行Md5
            imei = DigestUtils.md5DigestAsHex(imei.getBytes());
            baseParamsMap.put("imeiMd5", imei.toUpperCase());
        }



        List<String> tempList = new ArrayList<>();
        for(String key: baseParamsMap.keySet()){
            tempList.add(key+"="+baseParamsMap.get(key));
        }
        String requestParameters = String.join("&", tempList);
        String reportResultsStr = "";
        if("POST".equals(requestType)){
            reportResultsStr = HttpUtils.sendPost(requestAddress, requestParameters, ip, ua);
        }else{
            reportResultsStr = HttpUtils.sendGet(requestAddress, requestParameters, ip, ua);
        }

        JSONObject reportResults = null;
        try {
            reportResults = JSONObject.parseObject(reportResultsStr);
//            return reportResults==null?"":reportResults;
            if(reportResults.getInteger("code") == 0){
                return reportResults.getJSONObject("data").getInteger("bidStatus");
            }
            return 0;
        }catch (Exception e){
            e.printStackTrace();
        }
//        return reportResultsStr;
        return 0;
    }




    private String getMapValue(Map<String, Object> map, String key){
        if(map == null){
            return "";
        }
        if(map.get(key) == null){
            return "";
        }
        return map.get(key)+"";
    }





}
